/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.aptech.mBean;

import com.aptech.entities.TblOrder;
import com.aptech.entities.TblOrderDetail;
import com.aptech.entities.TblProject;
import com.aptech.entities.TblProjectDetail;
import com.aptech.entities.TblProjectDetailPK;
import com.aptech.mBean.util.JsfUtil;
import com.aptech.mBean.util.PaginationHelper;
import com.aptech.sBean.TblOrderDetailFacade;
import com.aptech.sBean.TblOrderFacade;
import com.aptech.sBean.TblProjectDetailFacade;
import com.aptech.sBean.TblProjectFacade;
import com.aptech.sBean.TblWorkingFacade;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import javax.faces.model.SelectItem;
import org.primefaces.event.ItemSelectEvent;
import org.primefaces.event.RowEditEvent;
import org.primefaces.model.chart.CartesianChartModel;
import org.primefaces.model.chart.LineChartSeries;

/**
 *
 * @author LanhAnh
 */
@ManagedBean(name = "orderController")
@SessionScoped
public class OrderController implements Serializable {

    @EJB
    private TblProjectDetailFacade tblProjectDetailFacade;
    @EJB
    private TblWorkingFacade tblWorkingFacade;
    @EJB
    private TblProjectFacade tblProjectFacade;
    @EJB
    private TblOrderDetailFacade tblOrderDetailFacade;
    @EJB
    private TblOrderFacade tblOrderFacade;
    private DataModel items = null;
    private PaginationHelper paginationHelper;
    private TblOrder current;
    private int selectedItemIndex;
    private List<TblOrder> listCustomerOrder;
    private DataModel itemsDetails = null;

    public List<TblOrder> listUserOrder(int usID) {
        return tblOrderFacade.getOrderByUserID(usID);
    }

    public List<TblOrder> listOrderBySatus() {
        return tblOrderFacade.getOrderByStatus();
    }

//    private List<TblOrder> listStatisticsOrder;
//
//    public List<TblOrder> getListStatisticsOrder(Date odCreateFrom, Date odCreateTo) {
//        return tblOrderFacade.Statistic(odCreateFrom, odCreateTo);
//    }
    /**
     * Creates a new instance of OrderController
     */
    public OrderController() {
        // createLinearModel();
    }

    public TblOrder getSelected() {
        if (current == null) {
            current = new TblOrder();
            selectedItemIndex = -1;
        }
        return current;
    }

    public TblOrderFacade getFacade() {
        return tblOrderFacade;
    }

    public PaginationHelper getPaginationHelper() {
        if (paginationHelper == null) {
            paginationHelper = new PaginationHelper(10) {
                @Override
                public int getItemsCount() {
                    return getFacade().count();
                }

                @Override
                public DataModel createPageDataModel() {
                    return new ListDataModel(getFacade().findRange(new int[]{getPageFirstItem(), getPageFirstItem() + getPageSize()}));
                }
            };
        }
        return paginationHelper;
    }

    public DataModel getItems() {
        if (items == null) {
            items = getPaginationHelper().createPageDataModel();
        }
        return items;
    }

    public DataModel getItemsDetails() {
        if (itemsDetails == null) {
            itemsDetails = getPaginationHelper().createPageDataModel();
        }
        return itemsDetails;
    }

    private void recreateModel() {
        items = null;
    }

    private void recreatePagination() {
        paginationHelper = null;
    }

    public String prepareView(TblOrder b) {
        current = b;
        return "OrderDetailManagement";
    }

    public String prepareViewDetailByClient(TblOrder b) {
        current = b;
        return "OrderDetailClient";
    }

    public String prepareList() {
        recreateModel();
        return "OrderManagement";
    }

    public void onEdit(RowEditEvent e) {
        FacesMessage msg = new FacesMessage("Edited Order", ((TblOrder) e.getObject()).getOdID().toString());
        FacesContext.getCurrentInstance().addMessage(null, msg);
        if (((TblOrder) e.getObject()).getOdStatus() == 1 && checkProjectWithOrder((TblOrder) e.getObject())) {
            createProjectWithOrder((TblOrder) e.getObject());
        }
        getFacade().edit((TblOrder) e.getObject());

    }

    public void onEditCancel(RowEditEvent e) {
        FacesMessage msg = new FacesMessage("Edit Order Cancelled", ((TblOrder) e.getObject()).getOdID().toString());
        FacesContext.getCurrentInstance().addMessage(null, msg);
    }

    public boolean checkProjectWithOrder(TblOrder tblOrder) {
        return tblProjectFacade.getTblProjectByOdID(tblOrder.getOdID()).isEmpty();
    }

    public void createProjectWithOrder(TblOrder tblOrder) {
        TblProject tblProject = new TblProject();
        tblProject.setOdID(tblOrder);
        tblProject.setPrState(1);
        tblProject.setPrCreated(new Date());
        tblProject.setPrEnable(Boolean.FALSE);
        tblProjectFacade.create(tblProject);

        List<TblOrderDetail> listTblOrderDetail = tblOrderDetailFacade.getTblOrderDetailByOdID(tblOrder.getOdID());
        for (int i = 0; i < listTblOrderDetail.size(); i++) {
            for (int j = 0; j < listTblOrderDetail.get(i).getOddQuantity(); j++) {
                TblProjectDetail pd = new TblProjectDetail();
                pd.setTblProject(tblProject);
                pd.setTblElevation(listTblOrderDetail.get(i).getTblElevation());
                pd.setWkID(tblWorkingFacade.getTblWorkingByWkID(1).get(0));
                TblProjectDetailPK tblProjectDetailPK = new TblProjectDetailPK();
                tblProjectDetailPK.setElID(listTblOrderDetail.get(i).getTblElevation().getElID());
                tblProjectDetailPK.setPrID(tblProject.getPrID());
                tblProjectDetailPK.setPdNo(j + 1);
                pd.setTblProjectDetailPK(tblProjectDetailPK);
                tblProjectDetailFacade.create(pd);
            }
        }

        FacesMessage msg = new FacesMessage("Project With Order Created");
        FacesContext.getCurrentInstance().addMessage(null, msg);
    }

    public SelectItem[] getItemsAvailableSelectMany() {
        return JsfUtil.getSelectItems(tblOrderFacade.findAll(), false);
    }

    public SelectItem[] getItemsAvailableSelectOne() {
        return JsfUtil.getSelectItems(tblOrderFacade.findAll(), true);
    }

    public String prepareCreate() {
        current = new TblOrder();
        selectedItemIndex = -1;
        return "Create";
    }

    public String create() {
        try {
            getFacade().create(current);
            return prepareCreate();
        } catch (Exception e) {
            return null;
        }
    }

    @FacesConverter(forClass = TblOrder.class)
    public static class OrderControllerConverter implements Converter {

        @Override
        public Object getAsObject(FacesContext context, UIComponent component, String value) {
            if (value == null || value.length() == 0) {
                return null;
            }
            OrderController controller = (OrderController) context.getApplication().getELResolver().
                    getValue(context.getELContext(), null, "orderController");
            return controller.tblOrderFacade.find(getKey(value));
        }

        @Override
        public String getAsString(FacesContext context, UIComponent component, Object object) {
            if (object == null) {
                return null;
            }
            if (object instanceof TblOrder) {
                TblOrder o = (TblOrder) object;
                return getStringKey(o.getOdID());
            } else {
                throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName() + "; expected type: " + TblOrder.class.getName());
            }
        }

        java.lang.Integer getKey(String value) {
            java.lang.Integer key;
            key = Integer.valueOf(value);
            return key;
        }

        String getStringKey(java.lang.Integer value) {
            StringBuffer sb = new StringBuffer();
            sb.append(value);
            return sb.toString();
        }
    }

    public void itemSelect(ItemSelectEvent event) {
        FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Item selected",
                "Item Index: " + event.getItemIndex() + ", Series Index:" + event.getSeriesIndex());

        FacesContext.getCurrentInstance().addMessage(null, msg);
    }
    private CartesianChartModel linearModel;

    public CartesianChartModel getLinearModel() {
        linearModel = new CartesianChartModel();
        LineChartSeries series1 = new LineChartSeries();
        series1.setLabel("Series 1");

        for (int i = 0; i <= 12; i++) {
//         series1.set(i + 1, i + 1);
            if (i < 10) {
                series1.set(i + 1, tblOrderFacade.Statistic("0" + i + 1 + ""));
            }
            series1.set(i + 1, tblOrderFacade.Statistic("" + i + 1));
        }

        linearModel.addSeries(series1);
        return linearModel;
    }
//    private void createLinearModel() {
//        linearModel = new CartesianChartModel();
//        LineChartSeries series1 = new LineChartSeries();
//        series1.setLabel("Series 1");
//
//        for (int i = 0; i <= 12; i++) {
//            // series1.set(i + 1, i + 1);
//            series1.set(i + 1, tblOrderFacade.Statistic(i + 1));
//        }
//
//        linearModel.addSeries(series1);
//
//
//    }
    //Statistic
    private Date dateStart = new Date(110, 01, 01);
    private Date dateEnd = new Date();

    public Date getDateStart() {
        return dateStart;
    }

    public void setDateStart(Date dateStart) {
        this.dateStart = dateStart;
    }

    public Date getDateEnd() {
        return dateEnd;
    }

    public void setDateEnd(Date dateEnd) {
        this.dateEnd = dateEnd;
    }
    private DataModel itemsStt = null;
    private List<TblOrder> order;

    public List<TblOrder> getOrder() {
        order = tblOrderFacade.getTblOrderByDateOdCreated(dateStart, dateEnd);
        return order;
    }

    // thông ke tong tiền.
    public int getTotal() {
        int total = 0;

        for (TblOrder o : getOrder()) {
            total += o.getOdTotal();
        }

        return total;
    }

    public DataModel getItemsStt() {
        if (itemsStt == null) {

            itemsStt = sttGetByDateCreated();

        }
        return itemsStt;
    }

    public DataModel prepareItemsStt() {

        itemsStt = sttGetByDateCreated();

        return itemsStt;
    }

    public void setItemsStt(DataModel itemsStt) {
        this.itemsStt = itemsStt;
    }

    public DataModel sttGetByDateCreated() {

        itemsStt = new ListDataModel(getFacade().getTblOrderByDateOdCreated(dateStart, dateEnd));
        return itemsStt;
    }

    public String sttView(TblOrder o) {
        current = o;
        return "/Admin/Order/OrderDetailManagement";
    }

    public SelectItem[] getItemStatus() {
        SelectItem[] selectItems = new SelectItem[4];
        selectItems[0] = new SelectItem("", "Select One");
        selectItems[1] = new SelectItem(0, "Not check");
        selectItems[2] = new SelectItem(1, "Successfull");
        selectItems[3] = new SelectItem(2, "Fail");
        return selectItems;
    }
}
